<template>
  <div>
    <el-dialog
      title="设计表单"
      :visible.sync="dialogVisible"
      :modal="true"
      :appendToBody="true"
      width="70%"
      v-dialog-drag
      :close-on-click-modal="false"
      top="5vh"
      @close="handleClose()"
      @open="handleOpen()"
    >
      <div v-loading="loading">
        <el-button
          type="default"
          class="preview-button"
          @click="handlePreviewForm"
          >预览</el-button
        >
        <!-- 基础信息设置 ---- start -->
        <el-form
          :model="baseForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="任务模板名称" prop="taskTemplateName">
                <span>{{ baseForm.taskTemplateName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="表单名称" prop="taskFormName">
                <el-input
                  v-model="baseForm.taskFormName"
                  type="text"
                  placeholder="请输入表单名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表单样式" prop="renderingMode">
                <!-- 有关联总部模板时，不可编辑 -->
                <el-radio-group
                  v-model="baseForm.renderingMode"
                  :disabled="!!baseForm.parentTaskTemplateCode"
                  @change="handleRenderingModeChange"
                >
                  <el-radio label="1">
                    常规式
                    <img
                      class="table-icon"
                      src="@/assets/images/form/mode_1.png"
                    />
                  </el-radio>
                  <el-radio label="2">
                    组合式
                    <img
                      class="table-icon"
                      src="@/assets/images/form/mode_2.png"
                    />
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- 基础信息设置 ---- end -->

        <!-- 表单设置 ---- start -->
        <div class="title">
          <PartitionTitle title="表单设置" type="line"></PartitionTitle>
        </div>

        <!-- 常规式，操作按钮 -->
        <div v-if="baseForm.renderingMode == '1'" class="tool-bar">
          <el-button type="primary" size="small" @click="handleAddRow()"
            >新增</el-button
          >
        </div>
        <!-- 组合式，操作按钮 -->
        <div v-if="baseForm.renderingMode == '2'" class="tool-bar">
          <el-button
            type="primary"
            size="small"
            @click="handleAddAndEditColumn()"
            >新增列</el-button
          >
          <el-button type="primary" size="small" @click="handleAddRow()"
            >新增行</el-button
          >
        </div>

        <el-table
          ref="StandardTable"
          :key="standarUpdate"
          :data="standardRows"
          tooltip-effect="dark"
          style="width: 100%; margin-bottom: 16px"
        >
          <!-- 标准内容列 -->
          <el-table-column
            v-for="(col, i) in standardColumns"
            :key="col.prop"
            :prop="col.prop"
          >
            <template slot="header" slot-scope="{ column, $index }">
              <!-- 常规式不显示编辑删除，组合式才显示 -->
              <span v-if="baseForm.renderingMode == '2'">
                标准内容{{ $index + 1 }}
                <i
                  class="el-icon-edit col-operate-icon"
                  @click="handleAddAndEditColumn(col)"
                ></i>
                <i
                  v-if="enbleDeleteCol(col)"
                  class="el-icon-delete col-operate-icon"
                  @click="handleDeleteColumn(col, 'standardColumns')"
                ></i>
              </span>
              <span v-else>表头</span>
            </template>
            <template slot-scope="{ row }">
              <el-input v-model="row[col.prop].label" type="text"></el-input>
            </template>
          </el-table-column>
          <!-- 表单字段列 -->
          <el-table-column
            v-for="(col, i) in formfieldColumns"
            :key="col.prop"
            :prop="col.prop"
          >
            <template slot="header" slot-scope="{ column, $index }">
              <!-- 常规式不显示编辑删除，组合式才显示 -->
              <span v-if="baseForm.renderingMode == '2'">
                表单字段{{ $index + 1 - standardColumns.length }}
                <i
                  class="el-icon-edit col-operate-icon"
                  @click="handleAddAndEditColumn(col)"
                ></i>
                <i
                  v-if="enbleDeleteCol(col)"
                  class="el-icon-delete col-operate-icon"
                  @click="handleDeleteColumn(col, 'formfieldColumns')"
                ></i>
              </span>
              <span v-else>字段设置</span>
            </template>
            <template slot-scope="{ row }">
              <el-popover placement="bottom" trigger="hover">
                <FieldDetail :form="row[col.prop]"></FieldDetail>
                <span slot="reference">
                  <span v-if="row[col.prop]">
                    {{
                      row[col.prop].componentType
                        ? componentTypeDictObj[row[col.prop].componentType]
                        : row[col.prop].associativePointerName || ""
                    }}
                  </span>
                  <el-button
                    type="text"
                    @click="handleAddAndEditFormField(row, col)"
                  >
                    设置
                  </el-button>
                </span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row }">
              <el-button
                v-if="enbleDeleteRow(row)"
                type="text"
                @click="handleDeleteStandardRow(row)"
                >删除</el-button
              >
              <el-button type="text" @click="handleMoveUpStandardRow(row)"
                >上移</el-button
              >
              <el-button type="text" @click="handleMoveDownStandardRow(row)"
                >下移</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 标准内容设置 ---- end -->
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saveloading" @click="handleSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 新增/编辑字段弹窗 -->
    <FormFieldDialog
      :visible.sync="formFieldDialog.visible"
      :row="formFieldDialog.row"
      :col="formFieldDialog.col"
      :taskTemplateDetail="baseForm"
      @refresh="addAndUpdateFormField"
    ></FormFieldDialog>

    <!-- 新增/编辑标准内容列弹窗 -->
    <StandardDialog
      :visible.sync="standardColumnDialog.visible"
      :row="standardColumnDialog.row"
      @refresh="addAndUpdateStandarColumn"
    ></StandardDialog>

    <!-- 表单预览 -->
    <PreviewDialog
      :visible.sync="previewDialog.visible"
      :formFieldConfig="previewDialog.formFieldConfig"
      :formName="baseForm.taskFormName"
      :renderingMode="baseForm.renderingMode"
    ></PreviewDialog>
  </div>
</template>
<script>
import FieldDetail from "./fieldDetail";
import FormFieldDialog from "./formFieldDialog";
import StandardDialog from "./standardDialog";
import PreviewDialog from "./previewDialog";
import {
  getTaskTemplateDetail,
  getTaskTemplateDesign,
  saveTaskTemplate,
  saveTaskTemplateDesign,
} from "@/api/taskMgmt/template";
export default {
  components: { FieldDetail, FormFieldDialog, StandardDialog, PreviewDialog },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
  },
  dicts: ["fieldType", "componentType"],
  data() {
    return {
      // 基础信息
      baseForm: {
        taskTemplateName: "",
        taskFormName: "",
        renderingMode: "1",
        parentTaskTemplateCode: null,
        associatedDevice: null,
      },
      // 基础信息校验规则
      rules: {
        taskFormName: [
          { required: true, message: "请输入表单名称", trigger: "change" },
        ],
        renderingMode: [
          { required: true, message: "请选择表单样式", trigger: "change" },
        ],
      },
      loading: false,
      saveloading: false,
      standarUpdate: 1,
      // 标准内容设置-行
      standardRows: [],
      // 标准内容设置-列
      standardColumns: [],
      // 表单字段设置-列
      formfieldColumns: [],
      // 标准内容设置新增/编辑列弹窗
      standardColumnDialog: {
        visible: false,
        row: null,
      },
      // 表单字段新增/编辑弹窗
      formFieldDialog: {
        visible: false,
        row: null,
        col: null,
      },
      // 表单预览弹窗
      previewDialog: {
        visible: false,
        formFieldConfig: {},
      },
      deleteHeadIdList: [],
      deleteFieldIdList: [],
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
    fieldTypeDictObj() {
      return this.dictToMap(this.dict.fieldType);
    },
    componentTypeDictObj() {
      return this.dictToMap(this.dict.componentType);
    },
  },
  methods: {
    handleClose() {
      this.$refs.ruleForm.resetFields();
      this.standardRows = [];
      this.standardColumns = [];
      this.formfieldColumns = [];
      this.deleteHeadIdList = [];
      this.deleteFieldIdList = [];
      this.baseForm = {
        taskTemplateName: "",
        taskFormName: "",
        renderingMode: "1",
        parentTaskTemplateCode: null,
        associatedDevice: null,
      };
    },
    handleOpen() {
      this.getTaskTemplateDetail();
      this.getTaskTemplateDesign();
    },
    // 查询模板详情
    getTaskTemplateDetail() {
      if (!this.row?.id) {
        return;
      }
      getTaskTemplateDetail(this.row.id)
        .then((res) => {
          const {
            taskTemplateName,
            taskFormName,
            renderingMode,
            parentTaskTemplateCode,
            associatedDevice,
          } = res.data;
          this.baseForm = {
            taskTemplateName,
            taskFormName: taskFormName || taskTemplateName, //表单名称没有值时，默认显示任务模板名称
            renderingMode: renderingMode || "1",
            parentTaskTemplateCode,
            associatedDevice,
          };
        })
        .catch(() => {
          this.baseForm = {
            taskTemplateName: null,
            taskFormName: null,
            renderingMode: "1",
            parentTaskTemplateCode: null,
            associatedDevice: null,
          };
        });
    },
    // 查询模板单据设计详情
    getTaskTemplateDesign() {
      if (!this.row?.taskTemplateCode) {
        return;
      }
      this.loading = true;
      getTaskTemplateDesign(this.row.taskTemplateCode)
        .then((res) => {
          const headLines = res.data?.headLines || [];

          if (headLines.length) {
            this.standardColumns = headLines[0].headList.map((e) => ({
              prop: `prop_standard_${e.id}`,
              sortIndex: e.sortIndex,
              cellType: "standardText",
            }));
            this.formfieldColumns = headLines[0].fieldList.map((e) => ({
              prop: `prop_field_${e.id}`,
              sortIndex: e.sortIndex,
              cellType: "formField",
            }));

            let standardRows = [];
            headLines.forEach((row) => {
              let obj = {
                id: `row_${row.titleCode}`,
                titleCode: row.titleCode,
              };
              this.standardColumns.forEach((col, colIndex) => {
                const cellObj = row.headList[colIndex];
                obj[col.prop] = {
                  ...cellObj,
                  label: cellObj.label || cellObj.label,
                };
                obj.titleIndex = cellObj.titleIndex; //用于行排序
              });

              this.formfieldColumns.forEach((col, colIndex) => {
                const cellObj = row.fieldList[colIndex];
                obj[col.prop] = {
                  ...cellObj,
                  optionSetting: JSON.parse(cellObj.optionSetting || "[]"),
                };
              });
              standardRows.push(obj);
            });
            this.standardRows = standardRows;
          } else {
            //  空模板,预留一个空的标准内容列和表单内容列
            this.setEmtyFormForRenderingMode1();
          }

          this.loading = false;
        })
        .catch((err) => {
          this.standardColumns = [];
          this.formfieldColumns = [];
          this.standardRows = [];

          this.loading = false;
        });
    },
    // 表单样式切换
    handleRenderingModeChange(value) {
      // 当组合式的标准内容、表单字段大于一列时，不支持切换常规式，此时提示“切换常规式，标准内容、表单字段不可多于一列”。
      if (value == "1") {
        // 切换到常规式
        if (
          this.standardColumns.length > 1 ||
          this.formfieldColumns.length > 1
        ) {
          this.msgWarning("切换常规式，标准内容、表单字段不可多于一列");
          this.baseForm.renderingMode = "2";
        }
      }

      // const standardprops = this.standardColumns.map((ele) => ele.prop);
      // const formfieldprops = this.formfieldColumns.map((ele) => ele.prop);
      // this.standardRows.forEach((row) => {
      //   standardprops.forEach((prop) => {
      //     // id存在说明这是一条已经存在数据库的数据，需要记录删除id
      //     if (row[prop].id) {
      //       this.deleteHeadIdList.push(row[prop].id);
      //     }
      //   });
      //   formfieldprops.forEach((prop) => {
      //     // id存在说明这是一条已经存在数据库的数据，需要记录删除id
      //     if (row[prop].id) {
      //       this.deleteFieldIdList.push(row[prop].id);
      //     }
      //   });
      // });

      // // 清空表单设置
      // if (value == "1") {
      //   // 常规式，设置默认表单
      //   this.setEmtyFormForRenderingMode1();
      // } else {
      //   this.standardRows = [];
      //   this.standardColumns = [];
      //   this.formfieldColumns = [];
      // }
    },
    //常规式的 空模板,预留一个空的标准内容列
    setEmtyFormForRenderingMode1() {
      const propIndex = new Date().getTime();
      const prop1 = (propIndex + 1).toString();
      const prop2 = (propIndex + 2).toString();
      this.standardColumns = [
        {
          prop: prop1,
          sortIndex: 1,
          cellType: "standardText",
        },
      ];
      this.formfieldColumns = [
        {
          prop: prop2,
          sortIndex: 1,
          cellType: "formField",
        },
      ];
      this.standardRows = [
        {
          id: `row_${new Date().getTime()}`,
          titleIndex: 1,
          [prop1]: {
            fieldSource: "custom",
            sortIndex: 1,
          },
          [prop2]: {
            fieldSource: "custom",
            sortIndex: 1,
          },
        },
      ];
    },
    // 标准内容设置 新增/编辑列按钮操作
    handleAddAndEditColumn(col) {
      this.standardColumnDialog.row = col || null;
      this.standardColumnDialog.visible = true;
    },
    // 标准内容设置 删除列按钮操作
    handleDeleteColumn(col, columnKey) {
      this.$confirm(`确定删除该列吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const deleteIndex = this[columnKey].findIndex(
          (ele) => ele.prop == col.prop
        );
        if (deleteIndex == -1) {
          return;
        }
        const deleteItems = this[columnKey].splice(deleteIndex, 1);
        const deleteItem = deleteItems[0];

        // 删除列后，行数据中对应的字段删除
        this.standardRows.forEach((row) => {
          // id存在说明这是一条已经存在数据库的数据，需要记录删除id
          if (row[deleteItem.prop].id) {
            if (columnKey == "standardColumns") {
              this.deleteHeadIdList.push(row[deleteItem.prop].id);
            } else if (columnKey === "formfieldColumns") {
              this.deleteFieldIdList.push(row[deleteItem.prop].id);
            }
          }
          // 删除对应字段
          delete row[deleteItem.prop];
        });

        this.msgSuccess("删除成功");
      });
    },
    // 标准内容设置 更新列数据
    addAndUpdateStandarColumn(row, rowData) {
      const columnKey =
        rowData.cellType == "standardText"
          ? "standardColumns"
          : "formfieldColumns";
      if (row) {
        // 编辑
        const colitem = this[columnKey].find((ele) => ele.prop == rowData.prop);
        colitem.prop = rowData.prop;
        colitem.sortIndex = rowData.sortIndex;
        colitem.cellType = rowData.cellType;
        if (this.standardRows.length) {
          this.standardRows.forEach((row) => {
            this.$set(row, rowData.prop, {
              ...row[rowData.prop],
              sortIndex: rowData.sortIndex,
            });
          });
        }
      } else {
        // 新增标准内容列
        this[columnKey].push({
          prop: rowData.prop,
          sortIndex: rowData.sortIndex,
          cellType: rowData.cellType,
        });
        if (this.standardRows.length) {
          this.standardRows.forEach((row) => {
            this.$set(row, rowData.prop, {
              label: "",
              fieldSource: "custom",
              sortIndex: rowData.sortIndex,
            });
          });
        }
      }
      // 排序
      this[columnKey].sort((a, b) => {
        return a.sortIndex >= b.sortIndex ? 1 : -1;
      });
      this.standarUpdate++;
    },
    // 标准内容设置 新增行按钮操作
    handleAddRow() {
      // 当前列表中所有的排序序号
      const paixuList = this.standardRows.map((ele) => ele.titleIndex);
      // 找出当前列表中所有的排序序号中最大的排序号
      let newpaixu = 0;
      if (paixuList?.length) {
        newpaixu = Math.max(...paixuList);
      }

      const obj = {
        id: `row_${new Date().getTime()}`,
        titleIndex: newpaixu + 1, //比最大的排序大1
      };

      this.standardColumns.forEach((c) => {
        obj[c.prop] = {
          label: "",
          fieldSource: "custom",
          sortIndex: c.sortIndex,
        };
      });

      this.formfieldColumns.forEach((c) => {
        obj[c.prop] = {
          label: "",
          fieldSource: "custom",
          sortIndex: c.sortIndex,
        };
      });

      this.standardRows.push(obj);
    },
    // 标准内容设置 删除行按钮操作
    handleDeleteStandardRow(row) {
      this.$confirm(`确定删除该行吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const delIndex = this.standardRows.findIndex((ele) => ele.id == row.id);
        if (delIndex == -1) {
          return;
        }

        // id存在说明这是一条已经存在数据库的数据，需要记录删除id
        this.standardColumns.forEach((col) => {
          if (row[col.prop].id) {
            this.deleteHeadIdList.push(row[col.prop].id);
          }
        });
        this.formfieldColumns.forEach((col) => {
          if (row[col.prop].id) {
            this.deleteFieldIdList.push(row[col.prop].id);
          }
        });

        // 删除行数据
        this.standardRows.splice(delIndex, 1);
        this.msgSuccess("删除成功");
      });
    },
    // 标准内容设置 上移行按钮操作
    handleMoveUpStandardRow(row) {
      const itemIndex = this.standardRows.findIndex((ele) => ele.id == row.id);
      if (itemIndex <= 0) {
        return;
      }
      // 交换排序号
      const prevPaixu = this.standardRows[itemIndex - 1].titleIndex;
      this.standardRows[itemIndex - 1].titleIndex =
        this.standardRows[itemIndex].titleIndex;
      this.standardRows[itemIndex].titleIndex = prevPaixu;
      // 更新数据
      this.sortStandarRow();
    },
    // 标准内容设置 下移行按钮操作
    handleMoveDownStandardRow(row) {
      const itemIndex = this.standardRows.findIndex((ele) => ele.id == row.id);
      if (itemIndex >= this.standardRows.length - 1) {
        return;
      }
      // 交换排序号
      const nextPaixu = this.standardRows[itemIndex + 1].titleIndex;
      this.standardRows[itemIndex + 1].titleIndex =
        this.standardRows[itemIndex].titleIndex;
      this.standardRows[itemIndex].titleIndex = nextPaixu;
      // 更新数据
      this.sortStandarRow();
    },
    // 标准内容设置 表格排序
    sortStandarRow() {
      this.standardRows.sort((a, b) => {
        return Number(a.titleIndex) >= Number(b.titleIndex) ? 1 : -1;
      });
    },
    // 表单设置 新增/编辑字段按钮操作
    handleAddAndEditFormField(row, col) {
      this.formFieldDialog.visible = true;
      this.formFieldDialog.row = row || null;
      this.formFieldDialog.col = col || null;
    },
    // 更新表单数据
    addAndUpdateFormField(row, col, rowData) {
      if (row) {
        // 更新某个字段
        let rowItemIndex = this.standardRows.findIndex(
          (ele) => ele.id == row.id
        );
        let rowItem = { ...this.standardRows[rowItemIndex] };
        rowItem[col.prop].fieldName = rowData.fieldName;
        rowItem[col.prop].fieldType = rowData.fieldType;
        rowItem[col.prop].associativePointer = rowData.associativePointer;
        rowItem[col.prop].associativePointerName =
          rowData.associativePointerName;
        rowItem[col.prop].fieldCode = rowData.fieldCode;
        rowItem[col.prop].defaultValue = rowData.defaultValue;
        rowItem[col.prop].componentType = rowData.componentType;
        rowItem[col.prop].isRequested = rowData.isRequested;
        rowItem[col.prop].optionSetting = rowData.optionSetting;
        rowItem[col.prop].warnType = rowData.warnType;
        rowItem[col.prop].warnValue = rowData.warnValue;

        this.$set(this.standardRows, rowItemIndex, rowItem);
      }
    },
    // 判断是否能删除行（总部的不能删）
    enbleDeleteRow(row) {
      let canDelFlag = true;
      const columns = [...this.standardColumns, ...this.formfieldColumns];
      const props = columns.map((ele) => ele.prop);
      for (let i = 0; i < props.length; i++) {
        const p = props[i];
        if (row[p] && row[p].fieldSource == "base") {
          // 存在总部的字段或标准内容，不能删除
          canDelFlag = false;
          break;
        }
      }
      return canDelFlag;
    },
    // 判断是否能删除列（总部的不能删）
    enbleDeleteCol(col) {
      const baseIndex = this.standardRows.findIndex(
        (row) => row[col.prop] && row[col.prop].fieldSource == "base"
      );
      if (baseIndex != -1) {
        // 存在总部的字段或标准内容，不能删除
        return false;
      }

      return true;
    },
    getParams() {
      const _standardRows = this.standardRows;
      const _standardColumns = this.standardColumns;
      const _formfieldColumns = this.formfieldColumns;
      let param = {
        taskTemplateCode: this.row.taskTemplateCode,
        headLines: [],
        headIdList: [...new Set(this.deleteHeadIdList)], //删除项
        fieldIdList: [...new Set(this.deleteFieldIdList)], //删除项
      };

      _standardRows.forEach((row) => {
        let headLineObj = {
          titleCode: row.titleCode || "",
        };

        headLineObj.headList = _standardColumns.map((col, colIndex) => {
          return {
            id: row[col.prop].id || null,
            titleCode: row[col.prop]?.titleCode || "",
            label: row[col.prop]?.label || "",
            fieldSource: row[col.prop]?.fieldSource || "custom",
            titleIndex: row.titleIndex,
            sortIndex: row[col.prop]?.sortIndex,
            fieldIndex: colIndex + 1, //当前所在数组的下标排序
          };
        });
        headLineObj.fieldList = _formfieldColumns.map((col, colIndex) => {
          return {
            id: row[col.prop].id || null,
            titleCode: row[col.prop]?.titleCode || "",
            parentFieldCode: col.parentFieldCode,
            fieldCode: row[col.prop]?.fieldCode || "",
            fieldName: row[col.prop]?.fieldName || "",
            fieldType: row[col.prop]?.fieldType || "",
            associativePointer: row[col.prop]?.associativePointer || "",
            associativePointerName: row[col.prop]?.associativePointerName || "",
            fieldSource: row[col.prop]?.fieldSource || "custom",
            componentType: row[col.prop]?.componentType || "",
            isRequested: row[col.prop]?.isRequested || "",
            titleIndex: row.titleIndex,
            sortIndex: row[col.prop]?.sortIndex,
            defaultValue: row[col.prop]?.defaultValue || "",
            optionSetting: JSON.stringify(row[col.prop]?.optionSetting || []),
            warnType: row[col.prop]?.warnType || "",
            warnValue: row[col.prop]?.warnValue || "",
            fieldIndex: colIndex + 1, //当前所在数组的下标排序
          };
        });
        param.headLines.push(headLineObj);
      });

      return param;
    },
    // 提交表单设置
    handleSubmit() {
      this.saveloading = true;

      const param1 = {
        id: this.row.id,
        taskFormName: this.baseForm.taskFormName,
        renderingMode: this.baseForm.renderingMode,
      };
      const param2 = this.getParams();

      // 校验，所有表单字段都必须配置好
      const emty = param2.headLines.findIndex((ele1) => {
        if (ele1.fieldList?.length) {
          // 判空条件：没有字段编码，或者字段类型为指标类的同时指标为空
          const emtyCode = ele1.fieldList.findIndex(
            (ele2) =>
              !ele2.fieldCode ||
              (ele2.fieldType == "1" && !ele2.associativePointer)
          );
          return emtyCode != -1;
        }
        return false;
      });
      if (emty != -1) {
        this.msgError("存在空的表单字段，请设置好所有的表单字段！");
        this.saveloading = false;
        return;
      }

      // 常规式，表单字段只能有一个时间字段，组合式，每行只能有一个时间字段
      // let isOverCount = false;
      // if (this.baseForm.renderingMode == "1") {
      //   // 常规式
      //   const dateFormFields = param2.headLines.filter((ele) => {
      //     const hasDateField = ele.fieldList.find((ele2) =>
      //       ["datetime", "date"].includes(ele2.componentType)
      //     );
      //     return !!hasDateField;
      //   });
      //   isOverCount = dateFormFields?.length > 1;
      // } else if (this.baseForm.renderingMode == "2") {
      //   // 组合式
      //   const dateFormFields = param2.headLines.filter((ele) => {
      //     const dateField = ele.fieldList.filter((ele2) =>
      //       ["datetime", "date"].includes(ele2.componentType)
      //     );
      //     return dateField.length > 1;
      //   });
      //   isOverCount = !!dateFormFields?.length;
      // }
      // if (isOverCount) {
      //   this.msgError("不支持添加2个时间字段！");
      //   this.saveloading = false;
      //   return;
      // }

      Promise.all([saveTaskTemplate(param1), saveTaskTemplateDesign(param2)])
        .then(([res1, res2]) => {
          if (res1.code == 200 && res2.code == 200) {
            this.msgSuccess("保存成功！");
            this.dialogVisible = false;
            this.$emit("refresh");
          }
        })
        .finally(() => {
          this.saveloading = false;
        });
    },
    // 预览表单
    handlePreviewForm() {
      this.previewDialog.visible = true;
      this.previewDialog.formFieldConfig = this.getParams();
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/element-variables.scss";
.table-icon {
  width: 20px;
  vertical-align: bottom;
  margin-left: 3px;
}
.tool-bar {
  margin-bottom: 10px;
}
.col-operate-icon {
  margin-left: 10px;
  font-size: 15px;
  cursor: pointer;
}
.title {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
  .block-title {
    margin-bottom: 0;
  }
}
::v-deep .el-dialog__body {
  position: relative;
  .preview-button {
    position: absolute;
    right: 20px;
    top: 30px;
    z-index: 2;
  }
}
</style>
